<template>
  <div>
    <el-drawer
      v-model="dialogVisible"
      :title="dialogStatus==='create'?'新增': (dialogStatus === 'view' ? '查看' : '编辑')"
      width="800px"
      @close="reset"
    >
      <div class="scene-dialog">
        <p>基本信息</p>
        <el-form 
          ref="articleFormRef"
          :model="formItem" 
          :rules="rules"
          label-width="100"
          label-position="top"
          :disabled="!isDisabled"
        >
          <el-form-item label="设备名称" prop="equipName">
            <el-input v-model="formItem.equipName" />
          </el-form-item>

          <el-form-item label="设备类型" prop="equipType">
            <el-select v-model="formItem.equipType" placeholder="请选择">
              <el-option v-for="item in equipList" :key="item.value" :label="item.name" :value="+item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="设备编号" prop="equipNum">
            <template v-if="dialogStatus === 'view'">
              <div class="view-text">{{ formItem.equipNum || '无' }}</div>
            </template>
            <template v-else>
              <el-input v-model="formItem.equipNum" placeholder="请输入设备编号" />
            </template>
          </el-form-item>

          <el-form-item label="设备状态" prop="equipStatus">
            <template v-if="dialogStatus === 'view'">
              <el-tag size="small" :type="getStatusTagType(formItem)">
                {{ getStatusLabel(formItem) }}
              </el-tag>
            </template>
            <template v-else>
              <el-select v-model="formItem.equipStatus" placeholder="请选择设备状态" clearable style="width: 100%;">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="所属商户" prop="tenantId">
            <template v-if="dialogStatus === 'view'">
              <div class="view-text">{{ getMerchantName() || '无' }}</div>
            </template>
            <template v-else>
              <el-select v-model="formItem.tenantId" placeholder="请选择商户" clearable filterable style="width: 100%;">
                <el-option v-for="item in merchantList" :label="item.tenantName" :value="item.id" :key="item.id" />
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="所在地点位置" prop="location">
            <template v-if="dialogStatus === 'view'">
              <div class="view-text">{{ formItem.location || '无' }}</div>
            </template>
            <template v-else>
              <div class="location-selector">
                <el-input v-model="formItem.location" placeholder="请选择地点位置" readonly style="margin-bottom: 8px;" />
                <el-button type="primary" @click="openLocationDialog" style="width: 100%;">
                  <el-icon>
                    <House />
                  </el-icon>
                  选择地点位置
                </el-button>
              </div>
            </template>
          </el-form-item>

          <el-form-item label="所属组织" prop="orgId">
            <org-tree-select 
              v-model="formItem.orgId" 
              @change="reloadList"
              style="width: 100%;"
            />
          </el-form-item>

          <el-form-item label="倍率" prop="multiplier">
            <el-input-number 
              v-model="formItem.multiplier" 
              :min="1" 
              :precision="0"
            />
          </el-form-item>
        
          <el-form-item label="设备描述" prop="equipDes">
            <el-input v-model="formItem.equipDes" />
          </el-form-item>

          <el-form-item label="设备图片:" prop="equipPic" class="add-no">
            <el-upload 
              :file-list="formItem.uploadPhotoDtoList"
              accept=".jpg,.jpeg,.png,.gif" 
              list-type="picture-card"
              :show-file-list="true"
              :action="`/base-api/file/upload`" 
              :headers="headers" 
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-remove="removeItem"
              :on-preview="handlePictureCardPreview"
              name="files"
              style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
              auto-upload
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  仅支持jpg、gif、png格式；大小为5M以内
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="关联网关" prop="gatewayId">
            <el-select v-model="formItem.gatewayId" placeholder="请选择">
              <el-option 
                v-for="item in netOption"
                :label="item.gatewayName" 
                :value="item.id" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="关联设备模板" prop="templateId">
            <el-select v-model="formItem.templateId" placeholder="请选择">
              <el-option 
                v-for="item in tempOption"
                :label="item.templateName" 
                :value="item.id" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="串口序号" prop="serialNumber">
            <el-select v-model="formItem.serialNumber" placeholder="请选择">
              <el-option 
                v-for="i in 20" 
                :key="i" 
                :label="`com${i}`" 
                :value="`com${i}`" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="MAC序列号" prop="macCode">
            <el-input v-model="formItem.macCode" />
          </el-form-item>

          <el-form-item label="供应商产品系列编号" prop="deviceType">
            <el-input v-model="formItem.deviceType" />
          </el-form-item>

          <el-form-item label="通信地址" prop="commAddress">
            <el-input v-model="formItem.commAddress" />
          </el-form-item>
          
        </el-form>
      </div>
        
      <template #footer v-if="isDisabled">
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus==='create'?createData():updateData()"
          >确 定</el-button>
        </span>
      </template>
    </el-drawer>
    <el-dialog v-model="dialogVisible2">
      <div style="text-align: center;">
        <img w-full :src="dialogImageUrl" alt="Preview Image" style="max-width: 100%;" />
      </div>
    </el-dialog>

    <!-- 地点位置选择对话框 -->
    <LocationSelectDialog ref="locationDialogRef" @confirm="handleLocationConfirm" />
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { House, Plus } from '@element-plus/icons-vue'
import { addEquip, editEquip, netList, tempList, getDist } from '@/api/collect'
import { getMerchantByName } from '@/api/settle'
import { validate } from '@/utils/validate'
import { getToken } from '@/utils/user';
import OrgTreeSelect from '@/components/OrgTreeSelect/index.vue'
import LocationSelectDialog from '@/views/settle/components/LocationSelectDialog.vue'

const netOption = ref([])

// 通用的列表获取函数
const fetchListData = async (
  apiFn: (id: any) => Promise<any>,
  id: any,
  dataKey: 'gatewayList' | 'templateList',
  targetRef: any
) => {
  if (!id) {
    targetRef.value = []
    return
  }
  try {
    const res = await apiFn(id)
    if (res.success && res.data && Array.isArray(res.data) && res.data.length > 0) {
      targetRef.value = res.data[0][dataKey] || []
    } else {
      targetRef.value = []
    }
  } catch (err: any) {
    console.error(`获取${dataKey === 'gatewayList' ? '网关' : '模板'}列表失败`, err)
    targetRef.value = []
  }
}

const getNetList = (id: any) => {
  fetchListData(netList, id, 'gatewayList', netOption)
}

const tempOption = ref([])

const getTempList = (id: any) => {
  fetchListData(tempList, id, 'templateList', tempOption)
}

const reloadList = () => {
  getNetList(formItem.orgId)
  getTempList(formItem.orgId)
}

const isDisabled = ref(true)

const formItem = reactive({
  id: null as number | null,
  equipName: '',
  equipNum: '',
  orgId: null,
  multiplier: null,
  equipType: null,
  equipDes: '',
  equipPic: '',
  gatewayId: null,
  templateId: null,
  serialNumber: '',
  macCode: '',
  deviceType: '',
  commAddress: '',
  tenantId: undefined as number | undefined,
  location: '',
  locationId: 0,
  uploadPhotoDtoList: [],
  equipStatus: null as number | null, 
})

const rules = reactive({
  equipName: [{ required: true, message: '请输入', trigger: 'blur' }],
  orgId: [{ required: true, message: '请选择', trigger: 'change' }],
  equipType: [{ required: true, message: '请输入', trigger: 'change' }],
})

const dialogVisible = ref(false)
const dialogStatus = ref('create')

const equipList = ref<any>([])

// 初始化设备类型列表
getDist('DC00011')
  .then((res: any) => {
    equipList.value = res.data
  })
  .catch((err: any) => {
    console.error('获取设备类型列表失败', err)
  })

// 设备状态选项（0-离线，1-在线，2-故障）
const statusOptions = [
  { label: '离线', value: 0 },
  { label: '在线', value: 1 },
  { label: '故障', value: 2 },
]

// 商户列表
const merchantList = ref<any[]>([])

// 获取商户列表
const getMerchantList = (name?: string) => {
  getMerchantByName(name).then((res: any) => {
    if (res.success && res.data) {
      merchantList.value = Array.isArray(res.data) ? res.data : []
    } else {
      console.warn('未获得到商户列表:', res)
      merchantList.value = []
    }
  }).catch((err: any) => {
    console.error('获取商户列表失败', err)    
  })
}

// 页面加载时获取商户列表
onMounted(() => {
  getMerchantList()
})

const reset = () => {
  formItem.uploadPhotoDtoList = []
  formItem.id = null
  if (!articleFormRef) return
  articleFormRef.value.resetFields()
  isDisabled.value = false
}

const articleFormRef = ref(null)

const emit = defineEmits(['listChange'])

const token = getToken();

const headers = { Authorization: `${token}` }

const handleUploadSuccess = (data: any) => {
  if (data.success === true) {
    formItem.equipPic = data.data[0]
    formItem.uploadPhotoDtoList = [{
      url: data.data[0],
      name: '设备图片'
    }]
    ElMessage.success(data.msg)
  } else {
    ElMessage.error(data.msg)
  }
}

const removeItem = (file: any) => {
  const removeIndex = formItem.uploadPhotoDtoList.findIndex((item: any) => {
    const itemUrl = item.url || item.uploadUrl || (item.response?.data?.[0])
    const fileUrl = file.url || file.uploadUrl || (file.response?.data?.[0])
    return itemUrl === fileUrl
  })
  if (removeIndex !== -1) {
    formItem.uploadPhotoDtoList.splice(removeIndex, 1)
    if (formItem.uploadPhotoDtoList.length === 0) {
      formItem.equipPic = ''
    }
  }
}

const handleUploadError = (err: any) => {
  try {
    const errorStr = err.toString().replace('UploadAjaxError: ', '')
    const errorObj = JSON.parse(errorStr)
    ElMessage.error(errorObj.msg || '上传失败')
  } catch (e) {
    ElMessage.error('上传失败，请重试')
  }
}

const dialogImageUrl = ref('')
const dialogVisible2 = ref(false)

const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible2.value = true
}

const createData = async () => {
  const valid = await validate(articleFormRef)
  if (valid) {
    addEquip(formItem)
    .then(() => {
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('创建成功！')
    })
    .catch(() => {
      dialogVisible.value = false
      ElMessage.error('创建失败！')
    })
  }
}

const updateData = async () => {
  const valid = await validate(articleFormRef)
  if (valid) {
    // 检查是否有 id（更新操作必须要有 id）
    if (!formItem.id) {
      ElMessage.error('缺少设备ID，无法更新')
      return
    }

    // 构建符合接口规范的请求数据
    const updateRequestData: {
      id: number
      commAddress?: string
      deviceType?: string
      equipDes?: string
      equipName?: string
      equipNum?: string
      equipPic?: string
      equipStatus?: number
      equipType?: number
      gatewayId?: number
      locationId?: number
      macCode?: string
      multiplier?: number
      orgId?: string
      serialNumber?: string
      templateId?: number
      tenantId?: number
    } = {
      id: formItem.id,
    }

    // 处理字符串类型字段（只添加有值的字段）
    const stringFields: Array<keyof typeof formItem> = [
      'equipName', 'equipNum', 'equipDes', 'equipPic', 'macCode', 'orgId', 'serialNumber', 'deviceType', 'commAddress'
    ]
    stringFields.forEach(field => {
      const value = formItem[field]
      if (value !== null && value !== undefined && value !== '') {
        updateRequestData[field] = value as any
      }
    })
    
    // 处理数字类型字段
    const numberFields: Array<keyof typeof formItem> = [
      'equipType', 'gatewayId', 'multiplier', 'templateId', 'tenantId', 'equipStatus'
    ]
    numberFields.forEach(field => {
      const value = formItem[field]
      if (value !== null && value !== undefined) {
        updateRequestData[field] = value as any
      }
    })
    
    // 处理 locationId（排除0）
    if (formItem.locationId && formItem.locationId !== 0) {
      updateRequestData.locationId = formItem.locationId
    }

    editEquip(updateRequestData)
    .then((res: any) => {
      if (res.success) {
        ElMessage.success('更新成功！')
        emit('listChange')
        setTimeout(() => {
          dialogVisible.value = false
        }, 100)
      } else {
        ElMessage.error(res.msg || '更新失败！')
      }
    })
    .catch((err: any) => {
      console.error('更新失败', err)
      ElMessage.error(err?.msg || '更新失败！')
    })
  }
}

// 获取商户名称
const getMerchantName = () => {
  if (!formItem.tenantId) return ''
  const merchant = merchantList.value.find((item: any) => item.id === formItem.tenantId)
  return merchant ? merchant.tenantName : ''
}

// 地点位置选择相关
const locationDialogRef = ref()

const openLocationDialog = () => {
  if (!formItem.tenantId) {
    ElMessage.warning('请先选择所属商户')
    return
  }
  
  if (locationDialogRef.value) {
    locationDialogRef.value.openDialog(formItem.tenantId)
  } else {
    ElMessage.error('地点位置选择组件未正确加载')
  }
}

const handleLocationConfirm = (selectedLocation: any) => {
  if (!selectedLocation) return
  
  const getLocationPath = (location: any): string => {
    if (location.path) return location.path
    if (location.parentPath) return `${location.parentPath} > ${location.name}`
    return location.name || '未知位置'
  }
  
  formItem.locationId = selectedLocation.id
  formItem.location = getLocationPath(selectedLocation)
  articleFormRef.value?.clearValidate('location')
}

type EquipmentStatus = 0 | 1 | 2 // 0-离线，1-在线，2-故障

const statusLabelMap: Record<number, string> = {
  0: '离线',
  1: '在线',
  2: '故障',
}

const resolveStatusCode = (row: any): EquipmentStatus | null => {
  const status = row?.equipStatus
  if (typeof status === 'number' && (status === 0 || status === 1 || status === 2)) {
    return status as EquipmentStatus
  }
  return null
}

const getStatusLabel = (row: any) => {
  const code = resolveStatusCode(row)
  return code !== null ? statusLabelMap[code] : '未知'
}

const getStatusTagType = (row: any) => {
  const code = resolveStatusCode(row)
  if (code === 1) return 'success' // 在线
  if (code === 0) return 'warning' // 离线
  if (code === 2) return 'danger' // 故障
  return 'info'
}

defineExpose({ dialogVisible, isDisabled, getNetList, getTempList, formItem, dialogStatus, reset })

</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 20px;
}
.add-no {
  :deep(.el-upload-list) {
    .el-upload-list__item + .el-upload {
      display: none;
    }
  }
}
.scene-dialog {
  margin-top: 10px;
  p {
    margin-top: 0;
  }
  &:after {
    content: '';
    display: table;
    clear: both;
  }
}
.location-selector {
  width: 100%;
}
.view-text {
  padding: 8px 0;
  color: #606266;
  min-height: 32px;
  line-height: 32px;
}
</style>
